import React from 'react'
import './PersonalCenter.css'
import { Button, Modal, Form, Input, Select, message } from 'antd';
import { getStorage, setStorage } from '../../utils/utils'
import UpDate from '../../components/upload'

const layout = {
    labelCol: {
        span: 5,
    },
    wrapperCol: {
        span: 16,
    },
};

class PersonalCenter extends React.Component {
    constructor() {
        super()
        this.state = {
            visible: false,
            user: '',
            newUser: '',
            BookcaseData: [],
            topupVisible: false,
            money: [60, 100, 200, 300, 500, 800, 1000, 1200],
            index: '',
        }
    }

    successPrompt = (val) => {
        message.success(val);
    };
    errorPrompt = (val) => {
        message.error(val);
    };

    componentDidMount() {
        this.getPersonDetails()
        this.getBookcase()
    }

    // 获取登录用户信息
    getPersonDetails = () => {
        this.axios({
            url: '/index/getPersonDetails',
            method: 'post',
            data: { userId: getStorage('user').Userid },
        }).then(data => {
            console.log(data.data.data[0])
            if (data.data.code === 200) {
                setStorage('user', data.data.data[0])
                this.setState({
                    user: data.data.data[0],
                })
            }
        })
    }

    // 确定修改
    handleOk = () => {
        this.axios({
            url: '/changePerson',
            method: 'post',
            data: this.state.user,
        }).then(data => {
            this.getPersonDetails()
            this.Child.uploadP()
        })
        this.setState({ visible: false });
    };

    onRef = (ref) => {
        this.Child = ref;
    }

    handleCancel = () => {
        this.setState({
            user: getStorage('user'),
            visible: false,
            topupVisible: false,
        })
    };

    // 修改用户信息
    changePerson(e, type) {
        const newUser = JSON.parse(JSON.stringify(this.state.user))
        newUser[type] = e.target.value
        this.setState({
            user: newUser,
        })
    }

    // 获取书架信息
    getBookcase() {
        if (getStorage('user').bookcase === null) {
            console.log(111)
        } else {
            let arr = getStorage('user').bookcase.split(',')
            let bookArr = []
            arr.forEach(item => {
                bookArr.push(parseInt(item))
            })
            this.axios({
                url: "/index/getBookCase",
                method: "post",
                data: { bookArr: bookArr },
            }).then(data => {
                this.setState({
                    BookcaseData: data.data.data
                })
            })
        }

    }

    // 获取书架li
    getBookCaseLi(List) {
        if (List) {
            return List.map((item, i) => {
                return (
                    <li key={i}>
                        <img onClick={() => this.gotoDetails(item)} alt='' src={"http://localhost:8888" + item.bookImg}></img>
                        <p onClick={() => this.gotoDetails(item)}>{item.bookName}</p>
                    </li>
                )
            })
        }
    }

    gotoDetails(item) {
        console.log(item)
        this.props.history.push({
            pathname: '/TotalEntry/BookDetails',
            state: { id: item.id }
        })
    }

    getMonetLi(List) {
        return List.map((item, i) => {
            return (
                <li onClick={() => this.choseMoney(i)} className={this.state.index === i ? 'choseMoney' : 'nochoseMoney'}>{item}阅币</li>
            )
        })
    }

    choseMoney(index) {
        console.log(index)
        this.setState({
            index: index,
        })
    }

    recharge() {
        if (this.state.index === '') {
            this.errorPrompt('请选择充值金额')
        } else {
            let topupMoney = this.state.money[this.state.index]
            this.axios({
                url: '/topupMoney',
                method: 'post',
                data: { userid: getStorage('user').Userid, money: topupMoney }
            }).then(data => {
                if (data.data.code === 200) {
                    this.successPrompt('充值成功')
                    this.getPersonDetails()
                    this.setState({
                        topupVisible: false,
                        index: '',
                    })
                }
            })
        }

    }

    render() {
        return (
            <div className='PersonalCenter'>
                <div className='big'>
                    <div className='personalDetails'>
                        <div className='detailsDiv1'>
                            <div>
                                <img alt='' src={'http://localhost:8888' + getStorage('user').HeadImg} ></img>
                                <p>{getStorage('user').UserName}</p>
                            </div>
                            <Button type="primary" onClick={() => this.setState({ visible: true })}>修改个人信息</Button>
                        </div>
                        <div className='detailsDiv2'>
                            <p>绑定手机：{getStorage('user').UserPhone}</p>
                            <p>电子邮箱：{getStorage('user').UserEmail}</p>
                            <p>个性签名：{getStorage('user').Signature}</p>
                        </div>
                    </div>
                    <div className='topUp'>
                        <p>阅币余额<span>{getStorage('user').balance}</span></p>
                        <Button type="primary" danger onClick={() => this.setState({ topupVisible: true })}>充值阅币</Button>
                        <Button>充值记录</Button>
                    </div>
                </div>

                <div className='bookcase'>
                    <p>我的书架</p>
                    <div className='bookList'>
                        <ul>
                            {
                                getStorage('user').bookcase ? (
                                    <>
                                        {this.getBookCaseLi(this.state.BookcaseData)}
                                    </>

                                ) : (
                                    <></>
                                )
                            }

                        </ul>
                    </div>
                </div>


                <Modal
                    visible={this.state.visible}
                    title="修改个人信息"
                    onOk={this.handleOk}
                    onCancel={this.handleCancel}
                    footer={[
                        <Button key="cancel" type="primary" onClick={() => this.handleCancel()}>取消</Button>,
                        <Button key="save" type="primary" onClick={() => this.handleOk()}>保存修改</Button>
                    ]}
                >
                    <Form {...layout} name="nest-messages">
                        <Form.Item label="头像">
                            <UpDate onRef={this.onRef}></UpDate>
                        </Form.Item>
                        <Form.Item label="用户名">
                            <Input onChange={(e) => this.changePerson(e, 'UserName')} value={this.state.user.UserName} />
                        </Form.Item>
                        <Form.Item label="性别">
                            <Select defaultValue={this.state.user.UserSex}>
                                <Select.Option value="男">男</Select.Option>
                                <Select.Option value="女">女</Select.Option>
                            </Select>
                        </Form.Item>
                        <Form.Item label="邮箱">
                            <Input onChange={(e) => this.changePerson(e, 'UserEmail')} value={this.state.user.UserEmail} />
                        </Form.Item>
                        <Form.Item label="个性签名">
                            <Input.TextArea onChange={(e) => this.changePerson(e, 'Signature')} value={this.state.user.Signature} />
                        </Form.Item>
                    </Form>
                </Modal>

                <Modal
                    visible={this.state.topupVisible}
                    title="充值阅币"
                    onCancel={this.handleCancel}
                    footer={[
                        <Button key="cancel" type="primary" onClick={() => this.handleCancel()}>取消</Button>,
                        <Button key="save" type="primary" onClick={() => this.recharge()}>确认充值</Button>
                    ]}
                >
                    <ul className='topupMoney'>
                        {this.getMonetLi(this.state.money)}
                    </ul>
                    <p style={{ marginTop: '15px' }}>支付金额：<span>{this.state.index === '' ? 0 : this.state.money[this.state.index] / 10}</span>元</p>
                </Modal>
            </div>
        )
    }
}
export default PersonalCenter